package sport

import (
	"github.com/bgmp/config"
	"github.com/bgmp/middleware"
	"github.com/bgmp/model"
	"github.com/gin-gonic/gin"
	"time"
)

func (b Base) Report(c *gin.Context, req *ReportRequest) *ReportResponse {
	req.EndTime.Time = time.Date(req.EndTime.Time.Year(), req.EndTime.Month(), req.EndTime.Day(), 23, 59, 59, 0, req.EndTime.Time.Location())
	response := ReportResponse{}

	delta := -24 * time.Hour

	condition := model.HeartSelectConditions{
		Start: model.Time{Time: req.EndTime.Time.Add(delta)},
		End:   model.Time{Time: req.EndTime.Time},
	}

	for i := 1; i <= 7; i++ {
		var dayReport DayReport
		hearts := model.ListHearts(config.DB,
			map[string]any{model.Diet_UserId: middleware.GetUserId(c)},
			&condition,
		)
		total := 0
		for _, heart := range hearts {
			total += heart.Heart
			if heart.Heart < dayReport.Lowest {
				dayReport.Lowest = heart.Heart
			} else if heart.Heart > dayReport.Highest {
				dayReport.Highest = heart.Heart
			}
		}
		if len(hearts) > 0 {
			dayReport.Average = float64(total) / float64(len(hearts))
		}

		//fmt.Println(fmt.Sprintf("%s %s", condition.Start.Time, condition.End.Time), diets)

		// 减少1天
		condition.Start.Time = condition.Start.Time.Add(delta)
		condition.End.Time = condition.End.Add(delta)

		response.Hearts = append(response.Hearts, dayReport)
	}

	return &response
}

type ReportRequest struct {
	EndTime model.Time `json:"end_time"`
}

type DayReport struct {
	Average float64 `json:"average"`
	Highest int     `json:"highest"`
	Lowest  int     `json:"lowest"`
}

type ReportResponse struct {
	Hearts []DayReport `json:"hearts"`
}
